package com.ct.ecommerce.idgen.service;

import com.ct.ecommerce.api.idgen.client.IdGeneratorService;
import com.ct.ecommerce.idgen.core.SnowflakeHolder;
import com.ct.ecommerce.idgen.core.SnowflakeIdWorker;
import com.ct.ecommerce.idgen.core.RecyclableZookeeperHolder;
import javax.annotation.PostConstruct;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author changtong
 * @since 2021/5/21
 */

@DubboService
public class IdGeneratorServiceImpl implements IdGeneratorService {

    @Value("${server.zk-address}")
    private String zkAddress;

    private SnowflakeIdWorker idWorker;

    @PostConstruct
    public void init(){
        SnowflakeHolder recyclableZookeeperHolder = new RecyclableZookeeperHolder(zkAddress);
        recyclableZookeeperHolder.init();
        idWorker = new SnowflakeIdWorker(recyclableZookeeperHolder.getWorkerId(),0);
    }

    @Override
    public Long get() {
        return idWorker.nextId();
    }
}
